<template>
  <el-row >
      <el-col :span="6">
        <el-tree
          :data="projectTrees"
          @node-click="onProjectSelected"
          node-key="value"
          highlight-current
          :default-expanded-keys="setDefaultKeys()"
          :current-node-key="projectKey"
        />
      </el-col>
      <el-col :span="18">
        <CreateProjectCom
          ref="projectRef"
          :projectKey="projectKey"
          @eventCallParentConfirm="callParentConfirm()"
          @eventCallParentCancel="callParentCancel()"
          @eventCallParentInited="setInited()"
        />
      </el-col>
    </el-row>
</template>

<script>
import useLocale from '@/languages/useLocale';
import { defineComponent, reactive, toRefs, ref, onMounted } from "vue";
import { clone,  } from "@/common/func";
import { keys } from "@/common/define";
import {useRouter} from "vue-router";
import { translate } from "@/common/translate";
import CreateProjectCom from '@/views/components/CreateProjectCom';
import {
  // 发送消息到vscode
  postMessage,
  isNoVscode,
  // 统一监听实现
  // commonListener,
} from "@/views/components/Global";


export default defineComponent({
  name: "CreateProjectTrees",
  props: {
    // itemCurrent: Object,
    // key: String,
  },
  components: {
    CreateProjectCom,
  },
  setup(props, context) {
    const propss = toRefs(props);

    onMounted(() => {
    });

    // const resetForm = () =>{
    //   console.log("resetForm")
    //   console.log(projectRef)
    //   projectRef.value.resetFields();
    //   // state.dataModel = []
    //   // state.modelMap = new Map();
    //   // state.step = 1;
    //   // state.stepMax = 1;
    //   // state.projectItems = [];
    // }
    const state = reactive({
      projectTrees : require("@/json//projectTrees.json"),
      projectKey: keys["KEY-C"],
      projectItem: undefined
    });
  　const projectRef = ref(null);
    const resetForm = () => {
      console.log(projectRef)
        projectRef.value.resetForm()
    }
    const {
      i18n: { t }, // 解构实例用具t 访问语言变量
      setLocale, //当前国际化
    } = useLocale();
    const router = useRouter();
    const initJson = () =>{
      console.log("initJson");
      // console.log(state.projectTrees);
      // console.log(state.projectTrees.createOptions);

      let projectsOptions = clone(state.projectTrees.createOptions);
      if(projectsOptions === undefined){
        projectsOptions = clone(state.projectTrees)
      }
      // console.log(projectsOptions);
      state.projectTrees = translate(t, projectsOptions);
      // console.log(state.projectTrees);
      // state.projectTrees.forEach( (item) => {
      //   console.log(item)
      // })
      
      sendParentProjectItem();
    };
    const setDefaultKeys = () => {
      const arr = [];
      arr.push(state.projectKey)
      return arr;
    };
    const onProjectSelected = (data) => {
      console.log(data)
      console.log("onProjectTreeSelected");
      console.log(data.children == undefined);
      if(data.children == undefined){
        // 根节点 选中
        state.projectKey = data.value;
        state.projectItem = getProjectItem();
      }
      sendParentProjectItem();
    }
    const callParentConfirm = () => {
      console.log(" --- callParentConfirm, projectKey:" + projectKey)
      context.emit("eventCallParentCancel", { projectKey: projectKey });

    };
    const callParentCancel = () => {
      console.log(" --- callParentCancel, projectKey:" + projectKey)
      context.emit("eventCallParentCancel", { projectKey: projectKey });

    };
    const sendParentProjectItem = () =>{
      console.log("sendParentProjectItem")
      console.log(state.projectKey)
      if(state.projectItem == undefined && state.projectTrees != undefined){
        state.projectItem = getProjectItem(state.projectTrees);
      }
      console.log("state.projectItem:")
      console.log(state.projectItem)
      context.emit('getComProjectItem', state.projectItem);
    };
    const getProjectItem = (trees) =>{
      let projectItem = undefined;
      console.log("getProjectItem:");
      if(trees != undefined){
      let len = trees.length;
      for(let i=0; i<len; i++){
        let item = trees[i];
        if(item.children != undefined){
          projectItem = getProjectItem(item.children)
          if(projectItem != undefined){
            return projectItem;
          }
        }else{
          if(item.value == state.projectKey){
            projectItem = item;
            return projectItem;
          }
        }
      }
      }
      // state.projectTrees.forEach( (item) => {
      // })
      console.log("getProjectItem:" + projectItem);
      return projectItem;
    }
    const listenerCallback = ({ data }) => 
      {
        console.log("addEventListener callback");
        console.log(data);
        try{
        
          if(data.error == true){
            state.error = true;
            state.errorMessage = data.message;
          }else if(data.type === 'init' && isNoVscode()){
            // 没有vscode时，并且初始化消息发送失败
            // 用于纯前端测试场景
            initJson();
          }else if (data.type === "LANGUAGE") {
            // 获取vscode语言
            console.log("LANGUAGE = " + data.value);
            // 设置插件语言
            setLocale(data.value);
            if(data.projectType !== undefined){
              state.key = data.projectType;
            }
            initJson();
          } else {
            console.log("Success!");
          }
        }catch(e){
          console.log(e);
        }finally{
          if(state.error){
            showError(state.errorMessage);
          }
        }
      }
      const setInited = () => {
        // 通知父级，初始化完成
        context.emit("eventCallParentInited", { });
      }
    return {
      t,
      ...toRefs(state),
      initJson,
      isNoVscode,
      postMessage,
      setInited,
      listenerCallback,
      onProjectSelected,
      projectRef,
      setDefaultKeys,
      resetForm,
      callParentConfirm,
      callParentCancel,
      getProjectItem,
      sendParentProjectItem
    };
  },
  unmounted(){
    console.log("function unmounted");
  },
  created() {
    try {
      console.log("function created");

      window.addEventListener("message", this.listenerCallback);

      if(this.isNoVscode()){
        this.initJson()
      }else{
        this.postMessage({ type: "init" });
      }
      // this.initJson()
    } catch (e) {
      console.log(e);
    }
    // console.log(getQuery());
  },
  methods: {},
});
</script>

<style>
.el-dialog__header {
  padding: 2px 10px;
}
.el-dialog__headerbtn {
  top: 3px;
}



.el-input__inner {
  height: 30px;
}
.el-button {
  height: 30px;
  min-height: 30px;
  padding: 6px 12px;
}
.el-header,
.el-footer {
  text-align: left;
}

.el-aside {
  text-align: center;
  line-height: 200px;
}

.el-main {
  text-align: center;
}

body > .el-container {
  margin-bottom: 40px;
}

.el-row {
  margin-bottom: 20px;
  /* &:last-child {
  margin-bottom: 0;
  } */
}
</style>
